<?php
/**
 * 会员模块
 */
namespace app\api\controller\user;

use app\api\controller\Common;
use app\api\model\user\Membermodel;
use think\facade\Env as getEnv;
use think\Db;
use wxxcx\WXBizDataCrypt;
use jwt\Jwt;

class Member extends Common {
    protected $data;
    public function initialize()
    {
        parent::initialize();
        $this->data = $this->request->except(['sign','accessKey','token']);
    }

    //微信登录
    public function wxLogin()
    {
        // 前台参数
        $code = input('post.code');

        //输入验证
        $this->checkParam([
            'code' => 'require|max:100',
        ]);

        // 小程序 appid 和 appsecret
        $appid     = config('xcx_appid');
        $appsecret = config('xcx_appsecret');

        // // 通过 code 用 curl 向腾讯服务器发送请求获取 session_key
        $wx_session = $this->jscode2session($appid, $appsecret, $code);
        if (isset($wx_session['errcode']) && $wx_session['errcode'] != 0) {
            return $this->showError($wx_session['errmsg'], 600);
        }

        // $wx_session['openid'] = 'openid-123';
        $user_info = db('users')->where(['openid' => $wx_session['openid']])->find();
        if (!$user_info) {
            $data = [];
            $data['openid']    = $wx_session['openid'];
            $data['reg_time'] = date('Y-m-d H:i:s');
            $data['user_type'] = 1;
            $data['nickname'] = '';
            $data['mobile'] = '';
            $data['photo'] = '';
            $data['status'] = 0;

            if (!db('users')->insert($data)) {
                return $this->showError('登录失败', 101);
            }

            $data['id'] = Db::name('users')->getLastInsID();
            #生成token
            $jwt = new Jwt;
            $payload = ['user_id' => $data['id'], 'openid' => $data['openid'], 'mobile' => $data['mobile'], 'iat' => time()];
            $data['token'] = $jwt->getToken($payload);
            trace(json_encode($data), 'new_user_wxlogin');
            return $this->showSuccess('登录成功', $data);
        } else {

            #生成token
            $jwt = new Jwt;
            $payload = ['user_id' => $user_info['id'], 'openid' => $user_info['openid'], 'mobile' => $user_info['mobile'], 'iat' => time()];
            $user_info['token'] = $jwt->getToken($payload);
            return $this->showSuccess('登录成功', $user_info);
        }
    }

    //微信授权登录
    public function wxAuthLogin()
    {
        // 前台参数
        $encryptedData = input('post.encryptedData');
        $code          = input('post.code');
        $iv            = input('post.iv');

        //输入验证
        $this->checkParam([
            'encryptedData' => 'require|max:2000',
            'code' => 'require|max:100',
            'iv' => 'require|max:40',
        ]);

        // 小程序 appid 和 appsecret
        $appid     = config('xcx_appid');
        $appsecret = config('xcx_appsecret');

        // 通过 code 用 curl 向腾讯服务器发送请求获取 session_key
        $wx_session = $this->jscode2session($appid, $appsecret, $code);
        $openid = $wx_session['openid'];
        if (isset($wx_session['errcode']) && $wx_session['errcode'] != 0) {
            return $this->showError($wx_session['errmsg'], 600);
        }

        // 用过 session_key 用 sdk 获得用户信息
        $wx_user = $this->getWxUserInfo($encryptedData, $iv, $wx_session['session_key'], $appid);
        trace($wx_user, 'wx_user');

        // 解密成功判断
        if (isset($wx_user['code']) && 10001 == $wx_user['code']) {
            return $this->showError('解密微信用户信息失败',103);
        }

        $user_info = Db::name('users')->where(['openid' => $openid])->find();
        if (!$user_info) {
            $data = [];
            $data['openid']    = $openid;
            $data['nickname']     = $wx_user['nickName'];
            $data['sex']      = $wx_user['gender'];
            $data['photo'] = $wx_user['avatarUrl'];
            $data['reg_time'] = date('Y-m-d H:i:s');
            $data['user_type'] = 1;
            $data['status'] = 0;
            $data['mobile'] = '';

            if (!Db::name('users')->insert($data)) {
                return $this->showError('用户数据插入失败','102');
            }

            $data['id'] = Db::name('users')->getLastInsID();
            #生成token
            $jwt = new Jwt;
            $payload = ['user_id' => $data['id'], 'openid' => $data['openid'], 'mobile' => $data['mobile'], 'iat' => time()];
            $data['token'] = $jwt->getToken($payload);
            return $this->showSuccess('授权登录成功', $data);
        } else {
            db('users')->where('id', $user_info['id'])->update([
                'nickname' => $wx_user['nickName'],
                'sex'    => $wx_user['gender'],
                'photo' => $wx_user['avatarUrl'],
            ]);
            #生成token
            $jwt = new Jwt;
            $user_info['sex'] = $wx_user['gender'];
            $user_info['nickname'] = $wx_user['nickName'];
            $user_info['photo'] = $wx_user['avatarUrl'];
            $payload = ['user_id' => $user_info['id'], 'openid' => $user_info['openid'], 'mobile' => $user_info['mobile'], 'iat' => time()];
            $user_info['token'] = $jwt->getToken($payload);
            return $this->showSuccess('授权登录成功', $user_info);
        }
    }

    /**
     * 前台用户登录
     */
    public function login(){
        $data = $this->data;
        $valid = $this->validate([
            'mobile' => $data['mobile'],
            'code' => $data['code']
        ],'app\api\validate\Members.login');
        if(true !== $valid){
            $this->return = ['status'=>200,'code'=>'GET_ERROR','message'=>$valid];
        }
        // elseif(cache('login-'.$data['mobile']) != $data['code']){
        //     $this->return = ['status'=>200,'code'=>'CODE_ERROR','message'=>'验证码错误！'];
        // }
        else{
            $login_data = [
                'mobile' => $data['mobile'],
                'code' => $data['code']
            ];
            $model = new Membermodel();
            $user = $model->loginUser($login_data);
            $jwt = new Jwt;
            $payload = ['user_id' => $user['id'], 'openid' => $user['openid'], 'mobile' => $user['mobile'], 'iat' => time()];
            $user['token'] = $jwt->getToken($payload);
            return $this->showSuccess('登录成功', $user);
            
        }
        
    }

    /**
     * 验证登录
     */
    public function checkLogin(){
        $post_token = input('token');
        $uid = $this->user['id'];
        $token = session_id();
        $login_flag = false;
        if($post_token == 'clgw*no*token'){
            $login_flag = true;
        }else{
            if($post_token && $uid && $token){
                if($uid && ($post_token == $token)){
                    $login_flag = true;
                }
            }
        }
//        if($post_token && $uid && $token){
//            if($uid && ($post_token == $token)){
//                $login_flag = true;
//            }
//        }
        if(true !== $login_flag){
            $this->return['status'] = 200;
            $this->return['code'] = 'GET_ERROR';
            $this->return['message'] = '您尚未登录';
            return $this->show($this->return);
        }else{
            $this->return['status'] = 200;
            $this->return['code'] = 'SUCCESS';
            $this->return['message'] = '已登录';
            return $this->show($this->return);
        }
    }
    /**
     * 前台用户注册 - 第一步
     */
    public function register(){
        // TODO 后续增加短信验证码验证逻辑
        $data = $this->data;
        $valid_res = $this->validate([
            'mobile' => $data['mobile'],
            'code' => $data['code']
        ],'app\api\validate\Members.login');
        if(true !== $valid_res){
            $this->return = ['status'=>200,'code'=>'GET_ERROR','message'=>$valid_res];
        }
        elseif(cache('reg-'.$data['mobile']) != $data['code']){
            $this->return = ['status'=>200,'code'=>'CODE_ERROR','message'=>'验证码错误！'];
        }
        else{
            $reg_info = [
                'mobile' => $data['mobile'],
                'reg_time' => date("Y-m-d H:i:s",time())
            ];
            $member = new Membermodel();
            $reg_res = $member->registerUser($reg_info);
            if(2 == $reg_res){
                $this->return = ['status'=>200,'code'=>'GET_ERROR','message'=>'手机号已注册'];
            }elseif(3 == $reg_res){
                $this->return = ['status'=>200,'code'=>'GET_ERROR','message'=>'注册失败'];
            }elseif(4 == $reg_res){
                $info = db('users')->where('mobile',$data['mobile'])->find();
                $datas = [
                    'uid'=>$info['id']
                ];
                $this->return = ['status'=>200,'code'=>'REG_NO_BASE','message'=>'注册但未编辑资料','data'=>$datas];
            }else{
                $datas = [
                    'uid'=>$reg_res
                ];
                $this->return = ['status'=>200,'code'=>'SUCCESS','message'=>'注册成功','data'=>$datas];
            }
        }
        return $this->show($this->return);
    }

    /**
     * 前台用户注册 - 第二步
     */
    public function regBaseInfo(){
        $data = $this->data;
        $valid = $this->validate([
            'realname' => $data['realname'],
            'birthday' => $data['birthday'],
            'address' => $data['address'],
            'email' => $data['email']
        ],'app\api\validate\Members.base');
        if(true !== $valid){
            $this->return = ['status'=>200,'code'=>'GET_ERROR','message'=>$valid];
        }else{
            $model = new Membermodel();
            $res = $model->regBase($data);
            if(2 == $res){
                $this->return = ['status'=>200,'code'=>'BASE_INFO_ERROR','message'=>'注册失败'];
            }else{
                $datas = [
                    'uid'=>$this->user['id'],
                    'mobile'=>session('mobile'),
                    'token' => session_id()
                ];
                $this->return = ['status'=>200,'code'=>'SUCCESS','message'=>'注册成功','data'=>$datas];
            }
        }
        return $this->show($this->return);
    }

    /**
     * 退出登录
     * @return int
     */
    public function logout(){
        session(null);
        $this->return = ['status'=>200,'code'=>'SUCCESS','message'=>'退出登录成功'];
        return $this->show($this->return);
    }

    /**
     * 获取微信用户信息
     *
     * @param string $appid 小程序 appId
     * @param string $appsecret 小程序 appSecret
     * @param string $code 登录时获取的 code
     * @return void
     */
    private function jscode2session($appid, $appsecret, $code)
    {
        // 拼接请求地址
        $url = 'https://api.weixin.qq.com/sns/jscode2session?appid='
        . $appid . '&secret=' . $appsecret . '&js_code='
        . $code . '&grant_type=authorization_code';

        $josn = httpRequest($url, 'get');
        trace($josn, 'jscode2session');
        $arr = json_decode($josn, true);

        return $arr;
    }

    //信息解密
    private function getWxUserInfo($encryptedData, $iv, $session_key, $APPID)
    {
        //进行解密
        $pc         = new WXBizDataCrypt($APPID, $session_key);
        $decodeData = "";
        $errCode    = $pc->decryptData($encryptedData, $iv, $decodeData);
        trace($decodeData, 'decryptData');
        trace($errCode, 'errCode');
        //判断解密是否成功
        if ($errCode != 0) {
            return [
                'code'    => 10001,
                'message' => 'encryptedData 解密失败',
            ];
        }
        //返回解密数据
        return json_decode($decodeData, true);
    }

    /**
     * 编辑基本信息 - 设置模块
     */
    public function updateUserInfo(){
        $this->checkUserLogin();
        $data = $this->data;
        $valid = $this->validate([
            'realname' => $data['realname'],
            'mobile' => $data['mobile'],
            'idcard' => $data['idcard'],
            'sex'=>$data['sex'],
            // 'code'=>$data['code']
        ], 'app\api\validate\Members.updateUserInfo');
        if (true !== $valid) {
            $this->showError($valid, 'PARAM_ERROR');
        }
        if(cache('user-'.$data['mobile']) != $data['code']){
            // $this->showError('验证码错误', 'CODE_ERROR');
        }

        $user_id = $this->user['id'];
        $data['user_id'] = $user_id;
        $model = new Membermodel();
        $res = $model->updateUserInfo($data);
        return $this->showSuccess('保存成功');
    }

    /**
     * 用户信息
     */
    public function getUserInfo()
    {
        $this->checkUserLogin();
        $uid = $this->user['id'];
        $info = db('users')->field('id,realname,mobile,sex,idcard,nickname,photo,user_type,status,account,idcard')->where('id', $uid)->find();
        //1-待支付 2-已支付 3-已发货 4-已完成 5-已取消 6-已退货 7-已退款 8-已关闭
        //non-paymen待支付，non-dispatch待发货，dispatch待收货，finish已完成 cancel已取消 refund退款
        $info['order']['non_paymen'] = db('order_info')->where('user_id', $uid)->where('order_type', 1)->where('order_status',1)->count();
        $info['order']['non_dispatch'] = db('order_info')->where('user_id', $uid)->where('order_type', 1)->where('order_status',2)->count();
        $info['order']['dispatch'] = db('order_info')->where('user_id', $uid)->where('order_type', 1)->where('order_status',3)->count();
        $info['order']['finish'] = db('order_info')->where('user_id', $uid)->where('order_type', 1)->where('order_status',4)->count();
        $info['order']['cancel'] = db('order_info')->where('user_id', $uid)->where('order_type', 1)->where('order_status',5)->count();

        return $this->showSuccess('用户信息', $info);
    }

    /**
     * 个人卖家入驻
     */
    public function saleUserReg(){
        $this->checkUserLogin();
        $data = $this->data;
        $uid = $this->user['id'];
        $files_people = $this->request->file('sale_card_one');   // 身份证正面
        $files_just = $this->request->file('sale_card_two');       // 身份证反面
        $flag = 0;
        $data_db['uid'] = $uid;
        if($files_people && $files_just && $data['sale_service_one'] && $data['sale_service_two'] && $data['sale_name'] && $data['sale_tel']){
            $info_people = $files_people->move(getEnv::get('root_path') . '/public/uploads');
            $info_just = $files_just->move(getEnv::get('root_path') . '/public/uploads');
            if($info_people){
                $data_db['sale_card_one'] = '/uploads/' . $info_people->getSaveName();
                $flag++;
            }else{
                $flag = 0;
            }
            if($info_just){
                $data_db['sale_card_two'] = '/uploads/' . $info_just->getSaveName();
                $flag++;
            }else{
                $flag = 0;
            }
            if(2 == $flag){
                $data_db['sale_service_one'] = $data['sale_service_one'];
                $data_db['sale_service_two'] = $data['sale_service_two'];
                $data_db['sale_name'] = $data['sale_name'];
                $data_db['sale_tel'] = $data['sale_tel'];
                $data_db['province'] = $data['province'];
                $data_db['city'] = $data['city'];
                $data_db['district'] = $data['district'];
                $data_db['sale_address'] = $data['sale_address'];
                $model = new Membermodel();
                $res = $model->saleUserRegModel($data_db);
                if(false !== $res){
                    $this->return = ['status'=>200,'code'=>'SUCCESS','message'=>'入驻成功'];
                }else{
                    $this->return = ['status'=>200,'code'=>'GET_ERROR','message'=>'入驻失败'];
                }
            }else{
                $this->return = ['status'=>200,'code'=>'GET_ERROR','message'=>'入驻失败'];
            }
        }else{
            $this->return = ['status'=>200,'code'=>'GET_ERROR','message'=>'入驻失败'];
        }
        return $this->show($this->return);
    }

    public function getUserId(){
        $time_data = implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1)));
        $times = substr($time_data,0,5) . rand(10,99);
        return $times;
    }
    // 根据生日获取星座
    public function getConstellationByBirthday($birthday){
        $month = intval(substr($birthday, 5, 2));
		$day = intval(substr($birthday, 8, 2));
		if ($month < 1 || $month > 12 || $day < 1 || $day > 31) {
            return NULL;
        }
		$signs = array(
            array('20' => '水瓶座'),
            array('19' => '双鱼座'),
            array('21' => '白羊座'),
            array('20' => '金牛座'),
            array('21' => '双子座'),
            array('22' => '巨蟹座'),
            array('23' => '狮子座'),
            array('23' => '处女座'),
            array('23' => '天秤座'),
            array('24' => '天蝎座'),
            array('22' => '射手座'),
            array('22' => '摩羯座')
        );
		list($start, $name) = each($signs[$month - 1]);
		if ($day < $start) {
            list($start, $name) = each($signs[($month - 2 < 0) ? 11 : $month - 2]);
        }
		return $name;
    }
    /**
     * 编辑个人介绍
     */
    public function introduction(){
        $this->checkUserLogin();
        $data = $this->data;
        $model = new Membermodel();
        $res = $model->baseUserIntroduction($data);
        if(1 == $res){
            $this->return = ['status'=>200,'code'=>'SUCCESS','message'=>'保存成功'];
        }else{
            $this->return = ['status'=>200,'code'=>'BASE_INFO_ERROR','message'=>'保存失败'];
        }
        return $this->show($this->return);
    }


    /**
     * 个人照片上传
     */
    public function photo(){
        $this->checkUserLogin();
        $data['uid'] = $this->user['id'];
        $data['create_time'] = date("Y-m-d H:i:s",time());
        $pics_data = $this->request->file('pics');
        $flag = 0;
        $pics_arr = [];
        if($pics_data){
            foreach ($pics_data as $key=>$file){
                $info = $file->move(getEnv::get('root_path') . '/public/uploads');
                if($info){
                    // TODO 百度云内容审核未开启，因为免费版有上限，待定
//                    $censor = new \Censor();
//                    $img_res = $censor->imageCensor(file_get_contents(getEnv::get('root_path') . '/public/uploads/' .$info->getSaveName()));
//                    if($img_res['conclusionType'] != 1){
//                        $this->return = ['status'=>200,'code'=>'DYNAMIC_PIC_VERIFY_ERROR','message'=>'图片内容违规'];
//                        return $this->show($this->return);
//                    }
                    $data['pic'] = '/uploads/' .$info->getSaveName();
                    $res = db('lj_users_photo')->insert($data);
                    if($res){
                        array_push($pics_arr,'/uploads/' .$info->getSaveName());
                        $flag++;
                    }
                }
            }
            $data['pics'] = $pics_arr;
        }
        if($flag > 0){
            $dynamic_data = [
                'uid' => $this->user['id'],
                'content' => '上传了照片',
                'create_time' => date("Y-m-d H:i:s",time()),
                'pics' => $pics_arr
            ];
            $dynamic = db('lj_users_dynamic')->json(['pics'])->insert($dynamic_data);
            if($dynamic){
                $this->return = ['status'=>200,'code'=>'SUCCESS','message'=>'成功'];
            }else{
                $this->return = ['status'=>200,'code'=>'DYNAMIC_SEND_ERROR','message'=>'动态发布失败'];
            }
        }else{
            $this->return = ['status'=>200,'code'=>'SEND_DYNAMIC_ERROR','message'=>'上传失败'];
        }
        return $this->show($this->return);
    }


    /**
     * 查询认证费商品详情
     * @return int
     */
    public function authProduct(){
        $model = new Membermodel();
        $res = $model->getAuthProduct();
        if(false !== $res){
            $this->return = ['status'=>200,'code'=>'SUCCESS','message'=>'成功','data'=>$res];
        }else{
            $this->return = ['status'=>200,'code'=>'NO_AUTH_PRODUCT_ERROR','message'=>"没有认证费商品"];
        }
        return $this->show($this->return);
    }

    /**
     * 缴纳认证费用-创建订单
     */
    public function authCreateOrder(){
        $this->checkUserLogin();
        // TODO 缺少已认证用户的验证
        $model = new Membermodel();
        $login = $model->checkLogin();
        if(false !== $login){
            $data = $this->data;
            $product_id = $data['product_id'];
            $uid = $data['uid'];
            if(!$product_id){
                $this->return = ['status'=>200,'code'=>'NO_PRODUCT_ID_ERROR','message'=>'请选择商品'];
            }else{
                $order_check = $model->selectOrder($product_id,$uid);    // 查询是否创建过订单
                if(false !== $order_check){
                    // 存在未支付订单，则不再创建，按照原有订单进行支付
                    $this->return = ['status'=>200,'code'=>'SUCCESS','message'=>'成功','data'=>$order_check];
                }else{
                    // 生成唯一订单号
                    $order_id = date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
                    $product_info = db('lj_product')->field('product_price')->where('id',$product_id)->find();
                    $order_info = [
                        'order_id' => $order_id,
                        'product_id' => $product_id,
                        'pay_money' => $product_info['product_price'],
                        'order_status' => 0,
                        'uid' => $uid,
                        'order_type' => 1,
                        'create_time' => date('Y-m-d H:i:s',time())
                    ];
                    $res = $model->createAuthOrder($order_info);
                    if(false !== $res){
                        $this->return = ['status'=>200,'code'=>'SUCCESS','message'=>'创建成功','data'=>$res];
                    }else{
                        $this->return = ['status'=>200,'code'=>'AUTH_CREATE_ERROR','message'=>'创建失败'];
                    }
                }
            }
        }else{
            $this->return = ['status'=>200,'code'=>'NO_LOGIN_ERROR','message'=>'您尚未登录'];
        }
        return $this->show($this->return);
    }

    /**
     * 填写邀请码
     */
    public function invitationCode(){
        $this->checkUserLogin();
        $request = $this->data;
        if($request['code']){
            $this->return = ['status'=>200,'code'=>'NO_INVITATION_CODE_ERROR','message'=>'请输入邀请码'];
        }else{
            $model = new Membermodel();
            $checkCode = $model->checkInvitationCode($request['code']);
            if(false !== $checkCode){
                $res = $model->writeInvitationCode($checkCode['id'],$request['uid']);
                if(false !== $res){
                    $this->return = ['status'=>200,'code'=>'SUCCESS','message'=>'成功'];
                }else{
                    $this->return = ['status'=>200,'code'=>'AUTH_INVITATION_CODE_ERROR','message'=>'保存失败'];
                }
            }else{
                $this->return = ['status'=>200,'code'=>'INVITATION_CODE_ERROR','message'=>'无效的邀请码'];
            }
        }
        return $this->show($this->return);
    }

    /**
     * 前台金币列表
     */
    public function goldProduct(){
        $model = new Membermodel();
        $res = $model->getGoldProduct();
        if(false !== $res){
            $this->return = ['status'=>200,'code'=>'SUCCESS','message'=>'成功','data'=>$res];
        }else{
            $this->return = ['status'=>200,'code'=>'NO_GOLD_PRODUCT_ERROR','message'=>"没有可购买的金币"];
        }
        return $this->show($this->return);
    }

    /**
     * 购买金币-创建订单
     */
    public function goldCreateOrder(){
        $this->checkUserLogin();
        $model = new Membermodel();
        $login = $model->checkLogin();
        if(false !== $login){
            $data = $this->data;
            $product_id = $data['product_id'];
            $uid = $data['uid'];
            if(!$product_id){
                $this->return = ['status'=>200,'code'=>'NO_PRODUCT_ID_ERROR','message'=>'请选择商品'];
            }else{
                $order_check = $model->selectOrder($product_id,$uid);    // 查询是否创建过订单
                if(false !== $order_check){
                    // 存在未支付订单，则不再创建，按照原有订单进行支付
                    $this->return = ['status'=>200,'code'=>'SUCCESS','message'=>'成功','data'=>$order_check];
                }else{
                    // 生成唯一订单号
                    $order_id = date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
                    $order_info = [
                        'order_id' => $order_id,
                        'product_id' => $product_id,
                        'order_status' => 0,
                        'uid' => $uid,
                        'order_type' => 3,
                        'create_time' => date('Y-m-d H:i:s',time())
                    ];
                    $res = $model->createAuthOrder($order_info);
                    if(false !== $res){
                        $this->return = ['status'=>200,'code'=>'SUCCESS','message'=>'创建成功','data'=>$res];
                    }else{
                        $this->return = ['status'=>200,'code'=>'AUTH_CREATE_ERROR','message'=>'创建失败'];
                    }
                }
            }
        }else{
            $this->return = ['status'=>200,'code'=>'NO_LOGIN_ERROR','message'=>'您尚未登录'];
        }
        return $this->show($this->return);
    }


}
